package com.siss.tenancy.user.utils;

import javax.crypto.Cipher;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class ShiHuaRSADESUtil {

	private static String KEY_RSA = "RSA";
	public final static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/CRMXY+Ep1APdpNFIDNfsXHx/hlL3F+hry8uNmZrGrYTm+rx5w64QYtco09vWP73eG8oRPxR3nXjTsklcmnfTot+QaJcTWkyRPKXlCI4uz5vM4XP8QvNVEG/6SuezIZzJYBbzUNdpTkB/IEw+8r15c2LTZ4O8EoFes8wqxfokXwIDAQAB";
	public static void main(String[] args) {
		
		String encrypt = encryptByPublic("{\"idNo\":\"520102197610254641\",\" time\":\"1546476043000\"}", publicKeyStr);
		System.out.println("===: "+encrypt);
	}
	
	 public static String encryptByPublic(String encryptingStr, String publicKeyStr) {
	        try {
	            byte[] publicKeyStrBytes = decryptBase64(publicKeyStr);
	            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyStrBytes);
	            byte[] data = encryptingStr.getBytes("UTF-8");
	            KeyFactory factory;
	            factory = KeyFactory.getInstance(KEY_RSA);
	            PublicKey publicKey = factory.generatePublic(keySpec);
	            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
	            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	            String string = encryptBase64(cipher.doFinal(data));
	            return URLEncoder.encode(string);
	        } catch (Exception e) {
//	            LOGGER.error("公钥加密失败", e);
	            throw new RuntimeException("公钥加密失败", e);
	        }
	    }
	 
	     public static byte[] decryptBase64(String key) {
	    	 
	        return Base64.getDecoder().decode(key);
	    }
	     public static String encryptBase64(byte[] key) {
		    return Base64.getEncoder().encodeToString(key);
		}
	 		    
}
